import 'package:flutter/material.dart';
import 'package:flutter_1/utils/db/DatabaseHelper.dart';
import 'package:flutter_1/utils/language/message.dart';
import 'package:flutter_1/utils/style.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:uuid/uuid.dart';

class OrderCreatePage extends StatefulWidget {
  @override
  _OrderCreatePageState createState() => _OrderCreatePageState();
}

class _OrderCreatePageState extends State<OrderCreatePage> {
  final _formKey = GlobalKey<FormState>();
  // 日期
  final _dateController = TextEditingController();
  // 产品名称
  final _productNameController = TextEditingController();
  // 数量
  final _quantityController = TextEditingController();
  // 单价
  final _unitController = TextEditingController();
  // 地址
  final _addressController = TextEditingController();
  // 联系人
  final _contactPersonController = TextEditingController();
  // 联系电话
  final _contactPhoneController = TextEditingController();
  // 备注
  final _remarkController = TextEditingController();

  String? _selectedCustomerCode;
  final List<String> _customerCodes = [];
  final _uuid = const Uuid();
  String _orderId = "";

  Future<void> _selectDate(BuildContext context) async {
    /// 日期选择
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime.now(),
      lastDate: DateTime(2100),
    );
    if (picked != null) {
      setState(() {
        _dateController.text = DateFormat('yyyy-MM-dd').format(picked);
      });
    }
  }

  @override
  void initState() {
    super.initState();
    queryUserList();
    _generateOrderId();
  }

  // 生成唯一订单号
  void _generateOrderId() {
    // 使用时间戳 + 随机数生成订单号
    String orderId = _uuid.v4(); // 生成一个唯一的UUID
    setState(() {
      _orderId = orderId;
    });
  }

  /// 查询用户表
  queryUserList() async {
    List<Map<String, dynamic>> res = await DatabaseHelper.query('User_table');
    setState(() {
      if (res.isNotEmpty) {
        for (var data in res) {
          _customerCodes.add(data["customer_code"] ?? "");
        }
      }
    });
  }

  /// 插入订单数据
  insertOrder() async {
    debugPrint("_selectedCustomerCode ----------- $_selectedCustomerCode");
    await DatabaseHelper.insert('Order_table', {
      "order_id": _orderId,
      "product_name": _productNameController.text,
      "quantity": _quantityController.text,
      "total_price": _unitController.text,
      "status": '1',
      "create_time": DateFormat('yyyy-MM-dd').format(DateTime.now()),
      "expected_delivery_date": _dateController.text,
      "customer_code": _selectedCustomerCode,
      "logistics_info": "济宁",
      "address": _addressController.text,
      "remarksInformation": _remarkController.text
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(Strem.createANewOrder,
            style: Style.c_white_size18_bold, textAlign: TextAlign.left),
        backgroundColor: Style.c_8cd5ff, // 设置AppBar背景色
        automaticallyImplyLeading: false, // 确保不显示返回按钮
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: ListView(
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(Strem.customerCode,
                      style: const TextStyle(fontSize: 16)),
                  const SizedBox(height: 5),
                  _buildCustomDropdown(),
                ],
              ),
              const SizedBox(height: 16),
              _buildTextField(Strem.productName,
                  controller: _productNameController),
              _buildTextField(Strem.quantity,
                  controller: _quantityController, isNumber: true),
              _buildTextField(Strem.unitPrice, controller: _unitController),
              _buildTextField(Strem.deliveryAddress,
                  controller: _addressController),
              _buildTextField(Strem.contact,
                  controller: _contactPersonController),
              _buildTextField(Strem.contactNumber,
                  controller: _contactPhoneController, isNumber: true),
              _buildTextField(Strem.remarksInformation,
                  controller: _remarkController),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(Strem.expectedDeliveryDate,
                      style: const TextStyle(fontSize: 16)),
                  const SizedBox(height: 5),
                  TextFormField(
                    controller: _dateController,
                    // enabled: false, // 禁止输入
                    readOnly: true, // 防止键盘弹出
                    decoration: InputDecoration(
                      contentPadding: const EdgeInsets.symmetric(
                          horizontal: 10, vertical: 12),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(5),
                        borderSide:
                            const BorderSide(color: Colors.grey), // 设置边框颜色
                      ),
                      suffixIcon: IconButton(
                        icon: const Icon(Icons.calendar_today),
                        onPressed: () => _selectDate(context), // 日期选择的回调函数
                      ),
                    ),
                    validator: (value) => value!.isEmpty
                        ? '${Strem.expectedDeliveryDate}${Strem.unempty}'
                        : null,
                  ),
                ],
              ),
              const SizedBox(height: 20),
              GestureDetector(
                onTap: () {
                  if (_formKey.currentState!.validate()) {
                    // 客户代码
                    if (_selectedCustomerCode == null ||
                        _selectedCustomerCode == "") {
                      Get.snackbar(
                        Strem.error,
                        '${Strem.customerCode}${Strem.unempty}',
                      );
                      return;
                    }
                    // 产品名称
                    if (_productNameController.text == "") {
                      Get.snackbar(
                        Strem.error,
                        '${Strem.productName}${Strem.unempty}',
                      );
                      return;
                    }
                    // 联系电话
                    if (_contactPhoneController.text.length != 11) {
                      Get.snackbar(
                        Strem.error,
                        '${Strem.contactNumber}${Strem.enterError}',
                      );
                      return;
                    }
                    insertOrder();
                    // 提示用户订单提交成功
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(content: Text(Strem.createSuccessful)),
                    );
                    Get.back();
                  }
                },
                child: Container(
                  margin: const EdgeInsets.only(bottom: 20),
                  width: MediaQuery.of(context).size.width - 32,
                  padding: const EdgeInsets.symmetric(vertical: 10),
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      color: Style.c_8cd5ff,
                      borderRadius: BorderRadius.circular(5)),
                  child: Text(
                    Strem.createANewOrder,
                    style: TextStyle(color: Colors.white, fontSize: 18),
                  ),
                ),
              ),
              GestureDetector(
                onTap: () {
                  Get.back();
                },
                child: Container(
                  margin: const EdgeInsets.only(bottom: 20),
                  width: MediaQuery.of(context).size.width - 32,
                  padding: const EdgeInsets.symmetric(vertical: 10),
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      color: Style.c_back38,
                      borderRadius: BorderRadius.circular(5)),
                  child: Text(
                    Strem.cancel,
                    style: TextStyle(color: Colors.white, fontSize: 18),
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  // 自定义下拉菜单
  Widget _buildCustomDropdown() {
    return GestureDetector(
      onTap: () {
        showMenu<String>(
          context: context,
          position: RelativeRect.fromLTRB(
            16, // 距离左边的距离
            150, // 距离顶部的距离（根据需要调整）
            MediaQuery.of(context).size.width - 16, // 距离右边的距离
            MediaQuery.of(context).size.height - 100, // 距离底部的距离
          ),
          items: _customerCodes.map((code) {
            return PopupMenuItem<String>(
              value: code,
              child: Text(code),
            );
          }).toList(),
          elevation: 8.0,
        ).then((value) {
          if (value != null) {
            setState(() {
              _selectedCustomerCode = value;
            });
          }
        });
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 12),
        decoration: BoxDecoration(
          border: Border.all(color: Colors.grey),
          borderRadius: BorderRadius.circular(5),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(_selectedCustomerCode ?? Strem.selectCode),
            const Icon(Icons.arrow_drop_down),
          ],
        ),
      ),
    );
  }

  // 统一样式的文本输入框组件
  Widget _buildTextField(String label,
      {required TextEditingController controller, bool isNumber = false}) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(label, style: const TextStyle(fontSize: 16)),
        const SizedBox(height: 5),
        TextFormField(
          controller: controller,
          keyboardType: isNumber ? TextInputType.number : TextInputType.text,
          decoration: InputDecoration(
            contentPadding:
                const EdgeInsets.symmetric(horizontal: 10, vertical: 12),
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(5),
              borderSide: const BorderSide(color: Colors.grey), // 设置边框颜色
            ),
          ),
          validator: (value) =>
              value!.isEmpty ? '$label${Strem.unempty}' : null,
        ),
        const SizedBox(height: 16),
      ],
    );
  }

  @override
  void dispose() {
    _dateController.dispose();
    _productNameController.dispose();
    _quantityController.dispose();
    _unitController.dispose();
    _addressController.dispose();
    _contactPersonController.dispose();
    _contactPhoneController.dispose();
    super.dispose();
  }
}
